package com.example.exam.controller;

import com.example.exam.constant.LoginConstant;
import com.example.exam.constant.TimeConstant;
import com.example.exam.pojo.Picture;
import com.example.exam.pojo.QuestionBank;
import com.example.exam.pojo.TestPaper;
import com.example.exam.pojo.User;
import com.example.exam.service.*;
import com.example.exam.utils.JsonUtil;
import com.example.exam.utils.R;
import lombok.RequiredArgsConstructor;
import org.springframework.http.HttpHeaders;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Base64;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author
 * @date 2023/03/05
 */
@RestController
@RequiredArgsConstructor
public class ClientController {

    private final TestPaperService testPaperService;
    private final UserService userService;
    private final QuestionBankService questionBankService;
    private final PictureService pictureService;

    private final RedisService redisService;

    /**
     *  查看题目
     */
    @GetMapping("/getQuestion")
    public Object getQuestion() {
        Object endObject = redisService.getObject(TimeConstant.END_TIME);
        long endTime = endObject == null ? Long.MAX_VALUE : (long) endObject;
        Map<String, Object> map = new HashMap<>(2);
        //题目列表
        List<QuestionBank> list = questionBankService.searchQuestionBankList();
        //题目
        map.put("question", list);
        //结束时间
        map.put("endTime", endTime);
        return R.ok(map);
    }

    /**
     *  查看已经提交的答案
     */
    @GetMapping("/getTestPaper/{tid}")
    public Object getTestPaper(@PathVariable int tid, HttpServletRequest request) {
        String sid = (String) request.getAttribute(LoginConstant.USER_ID);
        TestPaper paper = testPaperService.searchAllBySidAndTid(sid, tid);
        return R.ok(paper);
    }

    /**
     *  提交答案
     */
    @PostMapping("/submitTitle")
    public Object submitTitle(@RequestBody TestPaper testPaper, HttpServletRequest request) {
        String sid = (String) request.getAttribute(LoginConstant.USER_ID);
        testPaper.setSid(sid);
        TestPaper paper = testPaperService.searchAllBySidAndTid(sid, testPaper.getTid());
        //判断题目是否提交过
        if(paper != null) {
            //提交过就是修改
            testPaperService.updateAllBySidAndTid(testPaper);
        }else {
            //未提交就是添加
            testPaperService.insert(testPaper);
        }
        return R.ok();
    }

    /**
     *  预览答案
     */
    @GetMapping("/preview")
    public Object preview(HttpServletRequest request) {
        String sid = (String) request.getAttribute(LoginConstant.USER_ID);
        //答案列表
        List<TestPaper> list = testPaperService.searchAllBySid(sid);
        return R.ok(list);
    }

    /**
     *  提交试卷
     */
    @PostMapping("/submit")
    public Object submit(HttpServletRequest request) {
        //请求能进来,说明登录状态是对的,所以不需要对登录状态进行验证
        String token = request.getHeader(HttpHeaders.AUTHORIZATION);
        //将用户的token从redis数据库中删除
        redisService.del(LoginConstant.TOKEN_PREFIX + token);
        return R.ok();
    }

    /**
     *  查看图片
     */
    @GetMapping("/getPicture/{pictureName}")
    public void getPicture(@PathVariable String pictureName, HttpServletResponse response) throws IOException {
        OutputStream outputStream = null;
        try {
            response.setContentType("image/" + pictureName.split("\\.")[1]);
            response.setCharacterEncoding("utf-8");
            response.setHeader("Content-disposition", "attachment;filename=" + pictureName);
            //获取输出流
            outputStream = response.getOutputStream();
            Picture picture = pictureService.searchAllByPictureName(pictureName);
            outputStream.write(picture.getPictureData());
        }catch (IOException e) {
            response.reset();
            response.setContentType("application/json");
            response.setCharacterEncoding("utf-8");
            Map<String, String> map = new HashMap<>(3);
            map.put("status", "failure");
            map.put("message", "传输图片失败" + e.getMessage());
            response.getWriter().println(JsonUtil.toString(map));
        }finally {
            if(outputStream != null) {
                try {
                    outputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     *  登录
     */
    @PostMapping("/login")
    public Object login(@RequestBody User user) {
        //查询该用户是否存在
        User user1 = userService.searchAllBySid(user.getSid());
        if(user1 == null) {
            return R.fail("用户不存在,请联系工作人员!");
        }else if(user1.getLanguage() != null) {
            return R.fail("不能重复登录");
        }else {
            userService.login(user, user1.getLoginTime());
            String str = user.getSid() + ":" + user.getRecentlyTime();
            System.out.println(str);
            //生成token
            String token = Base64.getEncoder().encodeToString(str.getBytes());
            redisService.setObject(LoginConstant.TOKEN_PREFIX + token, user.getSid());
            return R.ok(token);
        }
    }
}
